<template>
  <view class="page">
    <view class="container" v-if="isLoginFlag">
      <scroll-view scroll-y class="scroll-view" enable-back-to-top>
        <view class="cart-header">
          <view class="select-all">
            <checkbox :checked="isAllSelected" @click="handleSelectAll"/>全选
          </view>
          <text class="clear-cart" @click="clearCart">清空购物车</text>
        </view>

        <!-- 按店铺分组展示商品列表 -->
        <view v-for="(group, index) in groupedCartItems" :key="index" class="shop-group">
          <view class="shop-header">
            <checkbox :checked="isShopAllSelected(group.shopId)" 
                     @click="toggleShopSelect(group.shopId)"/>
            <text class="shop-name">{{group.shopName}}</text>
          </view>
          
          <view class="goods-list">
            <view v-for="(item, itemIndex) in group.items" :key="itemIndex" class="goods-item">
              <view class="item-left">
                <checkbox :checked="item.isSelected" @click="toggleSelect(item)"/>
                <image :src="item.imgUrl" class="goods-image"></image>
              </view>

              <view class="item-right">
                <view class="goods-info">
                  <text class="goods-name">{{item.name}}</text>
                  <text class="goods-sales">月售{{item.sales}}件</text>
                  <view class="price-box">
                    <text class="current-price">¥{{item.price}}</text>
                    <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                  </view>
                </view>

                <view class="stepper">
                  <text class="btn minus" @click="decreaseQuantity(item)">-</text>
                  <text class="number">{{item.quantity}}</text>
                  <text class="btn plus" @click="increaseQuantity(item)">+</text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部结算栏 -->
        <view class="footer-bar" v-if="cartItems.length > 0">
          <view class="footer-left">
            <text class="total-text">合计：</text>
            <text class="total-price">¥{{totalPrice.toFixed(2)}}</text>
          </view>
          <button class="submit-btn" @click="handleCheckout">去结算({{selectedCount}})</button>
        </view>

        <!-- 空购物车提示 -->
        <view v-if="cartItems.length === 0" class="empty-cart">
          <image src="/static/images/empty-cart.png" class="empty-img"></image>
          <text class="empty-text">购物车当前为空</text>
          <button class="go-shopping" @click="goToIndex">去逛逛</button>
        </view>
      </scroll-view>
    </view>
    <view v-if="!isLoginFlag">
      <view class="register-link" @click="goTologin">还未登录，去登录</view>
    </view>
  </view>
  
</template>

<script>
	import  config  from '@/config'
export default {
  data() {
    return {
      isLoginFlag:false,
      cartItems: [],
      isAllSelected: false
    };
  },
  computed: {
    // 按店铺分组的购物车商品
    groupedCartItems() {
      const grouped = {};
      this.cartItems.forEach(item => {
        if (!grouped[item.superId]) {
          grouped[item.superId] = {
            shopName: item.storeName,
            shopId: item.superId,
            items: []
          };
        }
        grouped[item.superId].items.push(item);
      });
      return Object.values(grouped);
    },
    // 计算选中商品数量
    selectedCount() {
      return this.cartItems.filter(item => item.isSelected).length;
    },
    // 计算总价
    totalPrice() {
      return this.cartItems
        .filter(item => item.isSelected)
        .reduce((total, item) => total + (item.price * item.quantity), 0);
    }
  },
  onShow() {
    try {
      const value = uni.getStorageSync('token');
      const loginUserInfoJSON = uni.getStorageSync('loginUserInfo');
      if (value) {
        this.loginUserInfo = JSON.parse(loginUserInfoJSON);
        this.isLoginFlag = true;
      } else {
        this.isLoginFlag = false;
      }
    } catch (e) {
      console.error(e);
    }
	console.log(this.loginUserInfo)
    this.loadCartItems();
  },
  methods: {
    // 从本地存储加载购物车数据
    loadCartItems() {
      const items = uni.getStorageSync('cartItems') || [];
      this.cartItems = items.map(item => ({
        ...item,
        isSelected: item.isSelected || false
      }));
      this.checkAllSelected();
      console.log(this.cartItems)
    },
     goTologin(){
      uni.navigateTo({
                url: '/pages/login/index' 
            });
    },
    // 检查是否全选
    checkAllSelected() {
      this.isAllSelected = this.cartItems.length > 0 &&
        this.cartItems.every(item => item.isSelected);
    },
    
    // 检查店铺是否全选
    isShopAllSelected(shopId) {
      const shopItems = this.cartItems.filter(item => item.superId === shopId);
      return shopItems.length > 0 && shopItems.every(item => item.isSelected);
    },
    
    // 切换店铺全选状态
    toggleShopSelect(shopId) {
      const shopItems = this.cartItems.filter(item => item.superId === shopId);
      const shouldSelectAll = !this.isShopAllSelected(shopId);
      
      shopItems.forEach(item => {
        item.isSelected = shouldSelectAll;
      });
      
      this.updateCart();
      this.checkAllSelected();
    },

    // 切换单个商品选中状态
    toggleSelect(item) {
      item.isSelected = !item.isSelected;
      this.checkAllSelected();
      this.updateCart();
    },

    // 全选/取消全选
    handleSelectAll() {
      const selectAll = !this.isAllSelected;
      this.cartItems.forEach(item => {
        item.isSelected = selectAll;
      });
      this.isAllSelected = selectAll;
      this.updateCart();
    },

    increaseQuantity(item) {
      item.quantity++;
      this.updateCart();
    },

    decreaseQuantity(item) {
      if (item.quantity > 1) {
        item.quantity--;
      } else {
        this.removeItem(item);
      }
      this.updateCart();
    },

    updateCart() {
      uni.setStorageSync('cartItems', this.cartItems);
    },

    removeItem(item) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: (res) => {
          if (res.confirm) {
            const index = this.cartItems.findIndex(i => i._id === item._id);
            if (index !== -1) {
              this.cartItems.splice(index, 1);
              this.updateCart();
            }
          }
        }
      });
    },

    clearCart() {
      if (this.cartItems.length === 0) return;

      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: (res) => {
          if (res.confirm) {
            this.cartItems = [];
            uni.removeStorageSync('cartItems');
          }
        }
      });
    },

    handleCheckout(cartItems) {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        });
        return;
      }

      // 保存选中商品到本地，供结算页面使用
      const selectedItems = this.cartItems.filter(item => item.isSelected);
      uni.setStorageSync('selectedCartItems', selectedItems);
      uni.navigateTo({
        url: `/pages/address/index?selectedItems=${encodeURIComponent(JSON.stringify(selectedItems))}`
      });
    },
    
    goToIndex() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
};
</script>

<style scoped>
/* 基础样式 */
page {
  height: 100%;
  background-color: #f7f7f7;
}

.page {
  height: 100%;
}
.register-link {
    font-size: 16px;
    color: blue;
    text-decoration: underline;
    text-align: center;
    margin-top: 20px;
    cursor: pointer;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}

.scroll-view {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 120rpx;
}

/* 头部样式 */
.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  font-size: 28rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.clear-cart {
  color: #666;
}

/* 店铺分组样式 */
.shop-group {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
}

.shop-header {
  display: flex;
  align-items: center;
  padding: 20rpx 25rpx;
  background-color: #f9f9f9;
  border-bottom: 1rpx solid #eee;
}

.shop-name {
  font-size: 30rpx;
  font-weight: bold;
  margin-left: 15rpx;
  color: #333;
}

/* 商品列表样式 */
.goods-list {
  padding: 0 20rpx;
}

.goods-item {
  display: flex;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.goods-item:last-child {
  border-bottom: none;
}

.item-left {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-left: 15rpx;
}

.item-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-sales {
  font-size: 24rpx;
  color: #999;
  margin: 8rpx 0;
}

.price-box {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 32rpx;
  color: #e74c3c;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

/* 数量加减器 */
.stepper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.minus {
  background-color: #f5f5f5;
}

.plus {
  background-color: #1b76f6;
  color: #fff;
}

.number {
  margin: 0 20rpx;
  font-size: 28rpx;
  min-width: 40rpx;
  text-align: center;
}

/* 空购物车样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 100rpx;
}

.empty-img {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1b76f6;
  color: white;
  font-size: 30rpx;
  border-radius: 40rpx;
}

/* 底部结算栏 */
.footer-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 10;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.1);
  z-index: 100;
}

.footer-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.total-text {
  font-size: 28rpx;
  color: #333;
}

.total-price {
  font-size: 32rpx;
  color: #e74c3c;
  font-weight: bold;
  margin-left: 10rpx;
}

.submit-btn {
  width: 220rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1b76f6;
  color: white;
  font-size: 30rpx;
  border-radius: 40rpx;
  margin: 0;
  padding: 0;
}
</style>